package string;

/**
 * Created with IntelliJ IDEA.
 * Description: 151.反转字符串中的单词
 * User: Li_yizYa
 * Date: 2025—04—07
 * Time: 20:08
 */
public class Solution2 {
    public static void main(String[] args) {
        String s = "  the sky is   blue   ";
        System.out.println(reverseWords(s));
    }
    private static String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        // 去除多余空格
        StringBuilder sb = removeSpace(s);

        // 整体反转
        reverse(sb, 0, sb.length() - 1);

        // 反转每个单词
        int index = 0;// 记录左边界
        for (int i = 0; i < sb.length(); i++) {
            if (sb.charAt(i) == ' ') {
                reverse(sb, index, i - 1);
                index = i + 1;
            }
        }

        // 反转最后一组
        reverse(sb, index, sb.length() - 1);

        return sb.toString();
    }

    private static void reverse(StringBuilder sb, int left, int right) {
        while (left < right) {
            char c = sb.charAt(left);
            sb.setCharAt(left, sb.charAt(right));
            sb.setCharAt(right, c);
            left++;
            right--;
        }
    }

    private static StringBuilder removeSpace(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (s.charAt(left) == ' ') {
            left++;
        }
        while (s.charAt(right) == ' ') {
            right--;
        }
        StringBuilder sb = new StringBuilder();
        while (left <= right) {
            char c = s.charAt(left);
            if (c != ' ' || sb.charAt(sb.length() - 1) != ' ') {
                sb.append(c);
            }
            left++;
        }
        return sb;
    }
}
